package com.fatgirl.components
{
	import com.fatgirl.load.ILoadFactory;
	import com.fatgirl.load.LoadData;
	import com.fatgirl.utils.binding.DataBinding;

	/**
	 * 预加载器 
	 * @author iceman
	 * 
	 */
	public final class PreLoadFactory
	{
		private static var s_PreLoadFactory:PreLoadFactory;
		private var m_list:Array;
		private var m_completeFun:Function;
		private var m_loading:Boolean = false;
		public function PreLoadFactory()
		{
			if(s_PreLoadFactory) throw new FatError(FatError.SINGLETON_CLASS);
			m_list = new Array;
		}
		public static function getInstance():PreLoadFactory
		{
			if(!s_PreLoadFactory) s_PreLoadFactory = new PreLoadFactory;
			return s_PreLoadFactory;
		}
		/**
		 * 添加需要加载的数据URL，以及所使用的加载工厂 
		 * @param _url
		 * @param _loadFactory
		 * 
		 */
		public function addPreLoad(_url:String,_loadFactory:ILoadFactory):void
		{
			if(m_loading)throw new FatError(FatError.VALUE_IS_NULL);
			var t_preLoadObj:PreLoadObj = new PreLoadObj(_url,_loadFactory);
			m_list.push(t_preLoadObj);
		}
		/**
		 * 开始加载 
		 * @param _completeFun 加载完毕回调函数
		 * 
		 */
		public function startLoad(_completeFun:Function):void
		{
			m_loading = true;
			m_completeFun = _completeFun;
			ftrace(this,"开始预加载:"+m_list.length);
			loading();
		}
		/**
		 * 继续加载
		 * @param _obj
		 * 
		 */
		public function goOn(_obj:Object):void
		{
			loading();
		}
		private function loading():void
		{
			if(m_list.length)
			{
				var t_preLoadObj:PreLoadObj = m_list.shift();
				var loadData:LoadData = t_preLoadObj.loader.getData(t_preLoadObj.url);
				DataBinding.binding(this,"goOn",loadData,"data");
				ftrace(this,"预加载:"+t_preLoadObj.url);
			}
			else
			{
				m_loading = false;
				ftrace(this,"预加载完毕....");
				if(m_completeFun!=null) m_completeFun.call(null);
			}
		}
	}
}
import com.fatgirl.load.ILoadFactory;

class PreLoadObj
{
	public var url:String;
	public var loader:ILoadFactory;
	public function PreLoadObj(_url:String,_loadFactory:ILoadFactory)
	{
		url = _url;
		loader = _loadFactory;
	}
}